#pragma once
#include <iostream>
#include <fstream>
#include <memory>
#include <sstream>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>
#include <mutex>

namespace LogModule
{
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void Write(const std::string &message) = 0;

    protected:
        std::mutex _mutex;
    };

    // 控制台输出策略
    class ConsoleStrategy : public LogStrategy
    {
    public:
        void Write(const std::string &message) override
        {
            std::unique_lock<std::mutex> lockguard(_mutex);
            std::cout << message << std::endl;
        }
    };

    // 文件输出策略（支持路径和追加模式）
    class FileStrategy : public LogStrategy
    {
    public:
        explicit FileStrategy(const std::string &path = "/var/log/HttpWeb.log")
            : _file(path, std::ios::app)
        {
            if (!_file.is_open())
            {
                throw std::runtime_error("无法打开日志文件: " + path);
            }
        }

        void Write(const std::string &message) override
        {
            std::unique_lock<std::mutex> lockguard(_mutex);
            _file << message << std::endl;
        }

        ~FileStrategy()
        {
            _file.close();
        }

    private:
        std::ofstream _file;
    };

    enum class LogLevel
    {
        DEBUG,    // 调试信息
        INFO,     // 普通信息
        WARNING, // 警告
        ERROR,    // 错误
        FATAL     // 致命
    };

    std::string GetTimeStamp()
    {
        time_t cur = time(nullptr);
        struct tm tinfo;
        localtime_r(&cur, &tinfo);
        char buffer[128];
        sprintf(buffer, "%04d-%02d-%02d %02d:%02d:%02d", 1900 +\
                tinfo.tm_year, tinfo.tm_mon + 1, tinfo.tm_mday,
                tinfo.tm_hour, tinfo.tm_min, tinfo.tm_sec);
        return buffer;
    }

    std::string LevelToString(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    class Logger
    {
    public:
        // 构造时指定策略（默认控制台输出）
        explicit Logger(std::unique_ptr<LogStrategy> strategy = std::make_unique<ConsoleStrategy>())
            : _strategy(std::move(strategy))
        {
        }

        void SetStrategy(std::unique_ptr<LogStrategy> strategy)
        {
            _strategy = move(strategy);
        }

        class Message
        {
        public:
            Message(LogLevel level, const std::string filename, int line, Logger &logger)
                : _logger(logger)
            {
                char buffer[128];
                sprintf(buffer, "[%s] [%s] [%d] [%s] [%d] - ",
                        GetTimeStamp().c_str(), LevelToString(level).c_str(), getpid(), filename.c_str(), line);
                _loginfo = buffer;
            }

            template <typename T>
            Message &operator<<(const T &message)
            {
                std::stringstream buffer;
                buffer << message;
                _loginfo += buffer.str();
                return *this;
            }

            ~Message()
            {
                _logger._strategy->Write(_loginfo);
            }

        private:
            Logger &_logger;      // 引用外部logger类, 方便使用策略进行刷新
            std::string _loginfo; // 一条合并完成的，完整的日志信息
        };

        Message Log(LogLevel level, const std::string filename, int line)
        {
            return Message(level, filename, line, *this);
        }

        Message operator()(LogLevel level, const std::string filename, int line)
        {
            return Log(level, filename, line);
        }

    private:
        std::unique_ptr<LogStrategy> _strategy;
    };

    Logger logger;
    #define LOG(level) logger.Log(level, __FILE__, __LINE__)
    #define USE_CONSOLE_STRATEGY() logger.SetStrategy(std::make_unique<ConsoleStrategy>())
    #define USE_FILE_STRATEGY(...) logger.SetStrategy(std::make_unique<FileStrategy>(__VA_ARGS__))
}